import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class TcpServe1 {
    private ServerSocket tcpserve = null;

    public TcpServe1(int port) throws IOException {
        tcpserve = new ServerSocket(port);
    }

    public void start() throws IOException {
        //ExecutorService poll= Executors.newCachedThreadPool();
        System.out.println("服务器启动");
        while (true) {
            //使用这个socket1和具体的客户端进行交流
            Socket socket = tcpserve.accept();// //客户端在构造Socket对象的时候，就会指定服务器的IP和端口，如果没有客户端来连接，此时accept
            //就会阻塞,也就不会有socket这个对象
            Thread t=new Thread(()->{
                try {
                    connection(socket);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }


            });
            t.start();

        }
    }

    public void connection(Socket socket) throws IOException, InterruptedException {
        //System.out.println("服务器启动");
        System.out.printf("[%s:%d] 客户端上线!\n", socket.getInetAddress().toString(), socket.getPort());
        //由于要处理多个请求和响应，使用循环来进行
        try (OutputStream outputStream = socket.getOutputStream(); InputStream inputStream = socket.getInputStream()) {
            //Scanner scanner=new Scanner(inputStream);
            while (true) {
                //1.读取请求
                Scanner scanner = new Scanner(inputStream);
                if (!scanner.hasNext()) {
                    //System.out.println("服务器退出");
                    //没有下个数据。说明读完了（客户端关闭了连接）
                    System.out.printf("[%s:%d] 客户端下线!", socket.getInetAddress().toString(), socket.getPort());
                    break;
                }
                // 此处使用 next 是一直读取到换行符/空格/其他空白符结束, 但是最终返回结果里不包含上述 空白符
                String request = scanner.next();
                String response = process(request);
                PrintWriter writer = new PrintWriter(outputStream);
                writer.println(response);
                //此处使用println来写入，让结果中带有一个\n换行，方便对端来接收解析
                writer.flush();
                //flush 用来刷新缓冲区，保证当前写入的数据发送出去了
                System.out.printf("[%s:%d],req:%s;resp:%s\n", socket.getInetAddress().toString(), socket.getPort(),
                        request, response);

            }

        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            Thread.sleep(1000);
            socket.close();

        }
    }


    public String process(String request)
    {
        return request;

    }



    public static void main(String[] args) throws IOException {
        TcpServe1 tcpServe1=new TcpServe1(10001);
        tcpServe1.start();

    }
}


